<script setup>
import { ref, onMounted, defineEmits } from 'vue';
import { useRouter } from 'vue-router'; // 引入 useRouter
import http from '@/utils/api.js';

const router = useRouter(); // 初始化路由实例
const tableData = ref([]); // 商品数据
const total = ref(0); // 总数据量
const currentPage = ref(1); // 当前页码
const pageSize = ref(5); // 每页显示数量
const userLevel = ref(parseInt(localStorage.getItem('level')));

onMounted(async () => {
  await loadProducts();
});

// 加载商品数据
async function loadProducts() {
  try {
    const response = await http.get('/user/all', {
      params: {
        page: currentPage.value,  // 当前页码
        size: pageSize.value       // 每页数量
      }
    });
    // 处理返回数据
    tableData.value = response.data.records || []; // 获取商品记录
    total.value = response.data.total || 0; // 获取商品总数
  } catch (error) {
    console.error('加载用户失败:', error);
  }
}

// 编辑操作
function handleEdit(row) {
  // 跳转到 /editp 页面，传递商品 id
  router.push({ path: '/editu', query: { id: row.id } });
}

// 删除操作
async function handleDelete(row) {
  const confirmDelete = confirm(`是否确定要删除 ${row.name}?`);
  if (confirmDelete) {
    try {
      await http.delete(`/user/delete/${row.id}`);
      alert('删除成功');
      await loadProducts();
    } catch (error) {
      console.error('删除失败:', error);
    }
  }
}

// 分页改变时触发
function handleCurrentChange(page) {
  currentPage.value = page;
  loadProducts(); // 当前页码改变时重新加载数据
}
</script>

<template>
  <el-table :data="tableData" stripe style="width: 100%">
    <el-table-column prop="id" label="ID" width="100"/>
    <el-table-column prop="username" label="用户名" width="180"/>
    <el-table-column prop="gender" label="性别"/>
    <el-table-column prop="email" label="邮箱"/>
    <el-table-column prop="phone" label="电话"/>
    <el-table-column prop="createdAt" label="创建时间"/>
    <el-table-column align="center" label="操作" v-if="userLevel === 1" >
      <template #default="scope">
        <el-button size="small" style="width: 60px" @click="handleEdit(scope.row)" v-if="userLevel === 1" >编辑</el-button>
        <el-button
            v-if="userLevel === 1"
            size="small"
            type="danger"
            style="width: 80px"
            @click="handleDelete(scope.row)"
        >
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 分页 -->
  <el-pagination
      :total="total"
      :page-size="pageSize"
      :current-page="currentPage"
      layout="prev, pager, next"
      @current-change="handleCurrentChange"
  />
</template>

<style scoped>
</style>
